package com.novellotus.iov.carvice.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jakewharton.rxbinding2.widget.RxTextView;
import com.novellotus.httploadingview.LoadingView;
import com.novellotus.iov.carvice.R;
import com.novellotus.iov.carvice.adapter.CarScreenItemAdapter;
import com.novellotus.iov.carvice.adapter.StorageSearchAdapter;
import com.novellotus.iov.carvice.bean.RxVehicle;
import com.novellotus.iov.carvice.bean.RxVehiclesType;
import com.novellotus.iov.carvice.retrofit.BaseArrayEntity;
import com.novellotus.iov.carvice.retrofit.BaseArrayObserver;
import com.novellotus.iov.carvice.retrofit.BaseEntity;
import com.novellotus.iov.carvice.retrofit.BaseObserver;
import com.novellotus.iov.carvice.retrofit.RetrofitFactory;
import com.novellotus.iov.carvice.retrofit.RxSchedulers;
import com.novellotus.iov.carvice.rxjava.MyObserver;
import com.novellotus.iov.carvice.utils.MyUtils;
import com.novellotus.iov.carvice.utils.MyViewUtils;
import com.novellotus.iov.carvice.utils.SharedPreferencesUtils;
import com.novellotus.iov.carvice.view.CarScreenPopupWindow;
import com.novellotus.iov.carvice.view.PageView;
import com.orangegangsters.github.swipyrefreshlayout.library.RefreshLayout;
import com.orangegangsters.github.swipyrefreshlayout.library.RefreshLayoutDirection;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;

public class OutGoingActivity extends BaseActivity implements RefreshLayout.OnRefreshListener, LoadingView.OnBtnClickListener, PageView.PageViewInterface, CarScreenItemAdapter.CarScreenItemClickInterface, CarScreenPopupWindow.CarScreenPopupInterface {

    @BindView(R.id.tv_tittle)
    TextView tv_tittle;
    @BindView(R.id.btn_right)
    Button btn_right;
    @BindView(R.id.pageView)
    PageView pageView;
    @BindView(R.id.edt_vin)
    EditText edt_vin;
    @BindView(R.id.rlt_search)
    RelativeLayout rlt_search;
    @BindView(R.id.top)
    RelativeLayout top;

    private StorageSearchAdapter storageSearchAdapter;
    private CarScreenPopupWindow carScreenPopupWindow;

    private String eCode;
    private String rCode;
    private int pageSize = 10;
    private int report = 0;// report=1 表示数据未上报的车辆，report=2表示数据已上报的车辆 默认是report=0 表示查询所有车辆
    private int carType = 0;//0是所有状态车辆    1是入库车辆 2是出库车辆
    private String startTime = "";
    private String endTime = "";
    private String carModelId = "";
    private boolean isAdd;//是否新增状态
    private List<RxVehiclesType> rxVehiclesTypeList;
    private int carStatueChoosePosition = 0;
    private int carModelChoosePosition = 0;


    @Override
    protected void initContentView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_out_going);
    }

    @Override
    public void init() {
        eCode = getIntent().getStringExtra("eCode");
        rCode = getIntent().getStringExtra("rCode");
        edt_vin.clearFocus();
        tv_tittle.setText("出库管理");
        btn_right.setText("车辆出库");
        btn_right.setTextColor(Color.parseColor("#ffffff"));

        pageView.initLoadingView(this);
        pageView.refreshLayout.setOnRefreshListener(this);
        pageView.setPageViewInterface(this);
        pageView.loadingView.setOnBtnClickListener(this);
        pageView.setTotalPage(1, 1);
        pageView.setLoadCurrentPage(1);
        storageSearchAdapter = new StorageSearchAdapter(this, eCode, rCode, null, 2);
        pageView.setBottomInterface(storageSearchAdapter);
        pageView.setRecyclerViewAdapter(MyViewUtils.getLinearLayoutManager(this), storageSearchAdapter);
        pageView.loadingView.mWarnView.setTextColor(getResources().getColor(R.color.text_black));
        getModel();
        setSearchEdit();
    }

    //刷新多页内容
    int sizeNow = 10;

    @Override
    protected void onResume() {
        super.onResume();
        int sizeNow = pageView.getLoadCurrentPage() * 10;
        getList(1, sizeNow);
    }

    @OnClick(R.id.img_back)
    void back() {
        finish();
    }


    @OnClick(R.id.btn_right)
    void addCar() {
        carScreenPopupWindow.dismiss();
        pageView.setLoadCurrentPage(1);
        isAdd = !isAdd;
        carStatueChoosePosition = 0;
        initPopupWindow();
        storageSearchAdapter.changeStatue(isAdd);

        if (isAdd) {
            btn_right.setText("取消出库");
            tv_tittle.setText("选择出库车辆");
            report = 2;
            carType = 1;
            getList(1, 10);


        } else {
            btn_right.setText("车辆出库");
            tv_tittle.setText("出库管理");
            report = 0;
            carType = 0;
            getList(1, 10);
        }

    }


    /**
     * 设置搜索框
     */
    private void setSearchEdit() {
        RxTextView.textChanges(edt_vin).subscribe(new MyObserver<CharSequence>() {
            @Override
            public void onNext(CharSequence value) {
                super.onNext(value);
                getList(pageView.getLoadCurrentPage(), pageSize);
            }
        });
    }


    /**
     * 获取车辆列表
     */
    public void getList(int current, int size) {
        Observable<BaseEntity<RxVehicle>> observable = RetrofitFactory.getInstance().vehicles(SharedPreferencesUtils.getKey(this)[0], eCode, rCode, current, carType, edt_vin.getText().toString(), size, report, carModelId, startTime, endTime);
        observable.compose(RxSchedulers.<BaseEntity<RxVehicle>>compose())
                .subscribe(new BaseObserver<RxVehicle>(this) {

                    @Override
                    public void onSuccess(RxVehicle rxVehicle) {
                        pageView.loadSuccess();
                        if (rxVehicle != null) {
                            if (rxVehicle.getRecords() == null || rxVehicle.getRecords().size() == 0) {
                                if(isAdd){
                                    pageView.loadFail("无相关可出库车辆", false);
                                }else{
                                    pageView.loadFail("无相关车辆数据", false);
                                }

                            }
                            pageView.setTotalPage(rxVehicle.getTotal(), 10);
                            if (sizeNow == 10) {
                                if (rxVehicle.getCurrent() == 1) {
                                    storageSearchAdapter.updateList(rxVehicle.getRecords());
                                } else {
                                    storageSearchAdapter.addList(rxVehicle.getRecords());
                                }
                            } else {
                                //更新所有數據
                                sizeNow = 10;
                                storageSearchAdapter.updateList(rxVehicle.getRecords());
                            }
                        } else {
                            if(isAdd){
                                pageView.loadFail("无相关可出库车辆", false);
                            }else{
                                pageView.loadFail("无相关车辆数据", false);
                            }
                        }
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        pageView.loadFail(msg, true);
                    }

                    @Override
                    public void onError(String msg) {
                        pageView.loadFail(msg, true);
                    }
                });
    }

    /**
     * 获取车型列表
     */
    public void getModel() {
        Observable<BaseArrayEntity<RxVehiclesType>> observable = RetrofitFactory.getInstance().vehiclesTypes(SharedPreferencesUtils.getKey(this)[0], eCode, rCode);
        observable.compose(RxSchedulers.<BaseArrayEntity<RxVehiclesType>>compose())
                .subscribe(new BaseArrayObserver<RxVehiclesType>(this) {

                    @Override
                    public void onSuccess(List<RxVehiclesType> t) {
                        rxVehiclesTypeList = t;
                        initPopupWindow();
                    }

                    @Override
                    public void onFail(int code, String msg) {

                    }

                    @Override
                    public void onError(String msg) {
                    }

                });
    }

    private void initPopupWindow() {
        carScreenPopupWindow = new CarScreenPopupWindow(OutGoingActivity.this, OutGoingActivity.this, OutGoingActivity.this, rxVehiclesTypeList, carStatueChoosePosition, carModelChoosePosition, isAdd, startTime, endTime);

    }

    @OnClick(R.id.btn_screen)
    void screen() {
        MyUtils.hideInput(this);
        carScreenPopupWindow.showAsDropDown(rlt_search, 0, 0);
    }

    @Override
    public void loadData(int dataPage) {
        getList(pageView.getLoadCurrentPage(), pageSize);
    }

    @Override
    public void onReload() {
        getList(pageView.getLoadCurrentPage(), pageSize);
    }

    @Override
    public void onRefresh(RefreshLayoutDirection direction) {
        pageView.refreshData(direction);
    }

    @Override
    public void chooseStatue(int position) {
        //position 0 全部  1入库（全部） 2入库（未上报）3入库（已上报）4售出
        // report=1 表示数据未上报的车辆，report=2表示数据已上报的车辆 默认是report=0 表示查询所有车辆
        //carType 0是所有状态车辆   1是入库车辆 2是出库车辆
        switch (position) {
            case 0:
                carType = 0;
                report = 0;
                break;
            case 1:
                carType = 1;
                report = 0;
                break;
            case 2:
                carType = 1;
                report = 1;
                break;
            case 3:
                carType = 1;
                report = 2;
                break;
            case 4:
                carType = 2;
                report = 0;
                break;
        }
        carStatueChoosePosition = position;
    }

    @Override
    public void chooseModel(String id, int position) {
        carModelChoosePosition = position;
        if (position == 0) {
            carModelId = "";
        } else {
            carModelId = id;
        }
    }

    @Override
    public void clickCancel() {
        carScreenPopupWindow.dismiss();
    }

    @Override
    public void clickSearch() {
        pageView.setLoadCurrentPage(1);
        getList(pageView.getLoadCurrentPage(), pageSize);
        carScreenPopupWindow.dismiss();
    }

    @Override
    public void chooseStartTime(String startTime) {
        this.startTime = startTime;
    }

    @Override
    public void chooseEndTime(String endTime) {
        this.endTime = endTime;
    }
}
